/**
 * 根据指定的唯一键匹配两个对象数组，并将源数组对象中指定键的值累加到目标数组对象的指定键上。
 * @param {Object} targetObj - 目标参数对象
 * @param {Array} targetObj.arr - 目标对象数组
 * @param {string} targetObj.key - 目标数组对象的唯一键名
 * @param {string} targetObj.targetKey - 目标数组对象中要被累加的属性键名
 * @param {Object} sourceObj - 源参数对象
 * @param {Array} sourceObj.arr - 源对象数组
 * @param {string} sourceObj.key - 源数组对象的唯一键名
 * @param {string} sourceObj.sourceKey - 源数组对象中提供累加值的属性键名
 * @returns {Array} - 返回处理后的目标数组（注意：会修改原目标数组）
 */
function mergeArraysByKeyWithObjects (targetObj, sourceObj) {
	const { arr: targetArr, key: targetKey, targetKey: targetProp } = targetObj;
	const { arr: sourceArr, key: sourceKey, sourceKey: sourceProp } = sourceObj;

	// 参数基础校验
	if (!Array.isArray(targetArr) || !Array.isArray(sourceArr)) {
		throw new TypeError('Target and source must be arrays.');
	}
	if (typeof targetKey !== 'string' || typeof sourceKey !== 'string' ||
		typeof targetProp !== 'string' || typeof sourceProp !== 'string') {
		throw new TypeError('All key parameters must be strings.');
	}

	// 首先，遍历源数组，按sourceKey分组求和sourceProp的值
	const sumMapSource = new Map();
	for (const item of sourceArr) {
		if (item && item[sourceKey] !== undefined) {
			const currentSum = sumMapSource.get(item[sourceKey]) || 0;
			const valueToAdd = GetNumber(item[sourceProp]);
			sumMapSource.set(item[sourceKey], currentSum + valueToAdd);
		}
	}

	// 然后，遍历目标数组，根据targetKey从sumMapSource中获取总和，并累加到targetProp上
	for (const item of targetArr) {
		if (item && item[targetKey] !== undefined) {
			const totalFromSource = sumMapSource.get(item[targetKey]);
			if (totalFromSource !== undefined) {
				const currentValue = GetNumber(item[targetProp]);
				item[targetProp] = currentValue + totalFromSource;
			}
		}
	}

	return targetArr;
}

let GetNumber = function (str) {
	return Number(str) || 0;
};
let GetSum = function (arr) {
	return arr.reduce((acc, cur) => acc + GetNumber(cur), 0);
};
let myArr = {
	mergeArraysByKeyWithObjects,
	GetNumber,
	GetSum,
};
export default myArr;
